<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 企业媒体相关Controller v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\controller\enterprise;

use app\core\model\EnterpriseMedia;
use app\core\service\UploadService;
use ding\model\MediaTypeEnum;

/**
 * 企业媒体管理
 *
 * @package app\core\controller\enterprise
 */
class MediaController extends EnterpriseBaseController {

    /**
     * 媒体上传
     *
     * @throws \think\exception\DbException
     */
    public function upload() {
        $field = input("get.field", "file");
        $file = UploadService::save(request()->file($field));
        if (!$file || $file->getError()) {
            $this->error($file ? $file->getError() : "文件解析失败");
        }

        $fileInfo = $file->getInfo();
        $type = $this->getMediaType($fileInfo['type']);

        // 上传到钉钉
        $mid = input("get.mid");
        $apiHelper = $this->_getApiHelper($mid);
        $response = $apiHelper->mediaUpload($file->getPathname(), $type, $fileInfo['name']);
        $lastError = $apiHelper->getLastError();
        if (!empty($lastError)) {
            $this->error("存储失败：" . $lastError['errmsg']);
        }

        $mediaInfo = [
            'enterprise_id' => $this->eid,
            'module_id' => $mid,
            'filename' => $fileInfo['name'],
            'mime' => $fileInfo['type'],
            'size' => $fileInfo['size'],
            'type' => $type,
            'media_id' => $response['media_id'],
            'local' => str_replace("\\", "/", $file->getSaveName()),
            'gmt_upload' => date('Y-m-d h:i:s', $response['created_at'] / 1000)
        ];

        EnterpriseMedia::create($mediaInfo);

        $this->processViewUrl(false, $mediaInfo);
        $this->result($mediaInfo, 1);
    }

    /**
     * 获取显示媒体文件
     *
     * @throws \think\exception\DbException
     */
    public function get() {
        $mediaId = input("mediaId");
        $mid = input("mid");
        if (!$mediaId || empty($mid)) {
            $this->error("参数错误");
        }
        $apiHelper = $this->_getApiHelper($mid);
        echo $apiHelper->mediaDownloadFile($mediaId);
    }

    /**
     * 媒体列表查询
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function query() {
        $startDate = input("post.startDate");
        $endDate = input("post.endDate");
        $type = input("post.type");
        $keyword = input("post.keyword");
        $pageNum = input("post.pageNum", 1);
        $mid = input("post.mid");


        $dao = new EnterpriseMedia();
        $conditions = [];
        $conditions["enterprise_id"] = $this->eid;
        if ($startDate && $endDate) {
            $conditions['gmt_upload'] = ['between', [$startDate . " 00:00:00", $endDate . " 23:59:59"]];
        } else if ($startDate) {
            $conditions['gmt_upload'] = ['>=', $startDate . " 00:00:00"];
        } else if ($endDate) {
            $conditions['gmt_upload'] = ['<=', $endDate . " 23:59:59"];
        }
        if ($type && $type != 'all') {
            $conditions['type'] = $type;
        }
        if ($keyword) {
            $conditions['filename'] = ['like', "%" . $keyword . "%"];
        }
        if ($mid) {
            $conditions['module_id'] = $mid;
        }

        // 数据总条数
        $count = $dao->where($conditions)->count();
        $pageSize = 50;

        // 查询数据
        $rowObjs = $dao->where($conditions)->page($pageNum, $pageSize)->order("gmt_upload desc")->select();
        $rows = [];
        foreach ($rowObjs as $rowObj) {
            $row = $rowObj->getData();
            $this->processViewUrl(false, $row);
            $rows[] = $row;
        }

        return json([
            'code' => 1,
            'data' => [
                'rows' => $rows,
                'count' => $count,
                'pageNum' => $pageNum,
                'pageSize' => $pageSize
            ]
        ]);
    }

    /**
     * 根据mime类型获得媒体类型
     *
     * @param $mimeType
     * @return string
     */
    private function getMediaType($mimeType) {
        $items = explode("/", $mimeType);
        if ($items[0] == 'image') {
            return MediaTypeEnum::IMAGE;
        }
        if ($items[0] == 'audio') {
            return MediaTypeEnum::VOICE;
        }
        return MediaTypeEnum::FILE;
    }

    /**
     * 填充预览url
     *
     * @param $mid
     * @param $mediaInfo
     */
    private function processViewUrl($mid, &$mediaInfo) {
        if (!$mid) {
            $mediaInfo['url'] = '/' . UploadService::UPLOAD_DIR_NAME . "/" . $mediaInfo['type'] . "/" . $mediaInfo['local'];
        } else {
            $mediaInfo['url'] = '/core/enterprise.media/get?mid=' . $mid . "&mediaId=" . $mediaInfo['media_id'];
        }
        $mediaInfo['url'] = str_replace('\\', '/', $mediaInfo['url']);
    }
}